package teacher;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;
import core.modules.Institute;

public class Approvals extends InstituteListDAO {
	
	private Button getApproved;
	private CheckBox cb_approve;
	
	private List<Integer> list_approved = new ArrayList<Integer>();
	private Object[] array_approved;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teacher_approval_list);
		setTitle("Requests to join - " + getSubjectName());
		
		getApproved = (Button) findViewById(R.id.btn_getApproved);
		getApproved.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (list_approved.isEmpty()) {
					Toast.makeText(getApplicationContext(), "nothing selected!", Toast.LENGTH_SHORT).show();
				} else {
					array_approved = list_approved.toArray();
					new AsynchronousTask().execute("approve");
				}
			}
		});
		
		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				String item = av.getItemAtPosition(position).toString();
				
				int gid = Integer.valueOf(item.substring(item.indexOf("gid=")+4, item.indexOf("student=")-2));
				
				cb_approve = (CheckBox) view.findViewById(R.id.cb_approval);
				
				if (!cb_approve.isChecked()) {
					cb_approve.setChecked(true);
					list_approved.add(gid);
				} else {
					cb_approve.setChecked(false);
					list_approved.remove(list_approved.indexOf(gid));
				}
			}
		});
		
		new AsynchronousTask().execute("initialize");
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.teacher, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_logout:
	            	new Institute().Logout(this);
	            return true;	        	
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {
		
		ProgressDialog progressDialog;
		ListAdapter listAdapter;
		
		PreparedStatement pps;
		
		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
		
		String KEY_STUDENT = "student";
		String KEY_GRADESHEET_ID = "gid";
		
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(Approvals.this);
			progressDialog.setMessage("please wait...");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			
			try {
				if (args[0].equalsIgnoreCase("initialize")) {
					
					ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT gradesheet.id, CONCAT(users.firstname, ' ', users.lastname) AS 'student', users.studentid"
							+ " FROM gradesheet INNER JOIN users ON users.id = gradesheet.uid"
							+ " WHERE isApproved = 0 AND sid = " + getScheduleID());
					
					while (rs.next()) {
						m = new HashMap<String, String>();
						m.put(KEY_STUDENT, rs.getString("student"));
						m.put(KEY_GRADESHEET_ID, rs.getString("gradesheet.id"));
						
						arrayList.add(m);
						
					}
					
				}
				
				if (args[0].equalsIgnoreCase("approve")) {
					DatabaseConnector.getConnection().setAutoCommit(false);
					
					for (int i=0; i<=list_approved.size()-1; i++) {
						String query = "UPDATE gradesheet SET isApproved= 1 WHERE id = " + list_approved.get(i) + ";";
						DatabaseConnector.setPreparedStatement(query);
						pps = DatabaseConnector.getPreparedStatement();
						pps.executeUpdate();
					}
					pps.close();
				}
				
				
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}
			
			return null;
		}
		
		protected void onPostExecute(String postExecute) {
			
			progressDialog.dismiss();

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					listAdapter = new SimpleAdapter(
							Approvals.this, arrayList, R.layout.teacher_approval_detail,
							new String[] { KEY_STUDENT, KEY_GRADESHEET_ID},
							new int[] { R.id.tv_student});

					setListAdapter(listAdapter);
				}
			});
			
		}
		
	}

}